// API 请求封装 - 替代 background.js 的功能

// 获取解锁信息
async function getUnlockInfo() {
  const { storage } = await import('./storage.js')
  const result = await storage.get(['unlockCode', 'unlockTime', 'isUnlocked'])
  const code = sanitizeUnlockCode(result.unlockCode)
  const isUnlocked = !!result.isUnlocked
  const unlockTime = result.unlockTime || 0
  const elapsed = Date.now() - unlockTime
  const valid = isUnlocked && unlockTime && (elapsed < 12 * 60 * 60 * 1000)
  return { code, isUnlocked, valid }
}

// 构建解锁请求头
function buildUnlockHeaders(unlock) {
  const headers = {}
  if (!unlock || !unlock.isUnlocked || !unlock.valid || !unlock.code) return headers
  const code = sanitizeUnlockCode(unlock.code)
  if (!code) return headers
  headers['unlockcode'] = code
  return headers
}

// 清理解锁码
function sanitizeUnlockCode(raw) {
  if (!raw) return ''
  const first = String(raw).split(/[\s,;]+/).filter(Boolean)[0] || ''
  return first.trim()
}

// 搜索音乐
export async function searchTracks(keyword, page = 1, size = 30) {
  const q = encodeURIComponent(keyword || '')
  const p = Number(page) > 0 ? Number(page) : 1
  const s = Number(size) > 0 ? Number(size) : 30
  const api = `https://api.flac.life/search/kuwo?keyword=${q}&page=${p}&size=${s}`
  
  try {
    const res = await fetch(api, { credentials: 'omit', cache: 'no-store' })
    const data = await res.json()
    if (!data || data.success !== true || !data.result || !Array.isArray(data.result.list)) return []
    
    const items = data.result.list.map((x) => ({
      id: x.id,
      title: x.name,
      artist: Array.isArray(x.singers) ? x.singers.join('/') : '',
      album: x.albumName || '',
      duration: '',
      cover: x.picUrl || '',
      detailUrl: '',
      url: '',
      platform: x.platform || 'kuwo'
    }))
    return items
  } catch (error) {
    console.error('Search error:', error)
    return []
  }
}

// 验证解锁码
export async function verifyUnlockCode(code) {
  const api = `https://api.flac.life/unlock/${encodeURIComponent(code)}`
  
  try {
    const res = await fetch(api, { credentials: 'omit', cache: 'no-store' })
    const data = await res.json().catch(() => null)
    
    if (!data || data.code !== 200) {
      return { success: false, message: '解锁失败，请检查解锁码' }
    }
    
    return { success: true, message: '解锁成功！' }
  } catch (error) {
    console.error('Unlock error:', error)
    return { success: false, message: '网络异常，请稍后重试' }
  }
}

// 解析播放地址
export async function resolveStream(detailUrl, id, platform) {
  const trackId = id || detailUrl || ''
  const pf = platform || 'kuwo'
  if (!trackId) return { url: '' }
  
  const api = `https://api.flac.life/url/${encodeURIComponent(pf)}/${encodeURIComponent(trackId)}/128`
  
  try {
    const unlock = await getUnlockInfo()
    const headers = buildUnlockHeaders(unlock)
    
    // 首次尝试：带上解锁头，且包含凭证（Cookie）
    let r = await fetch(api, { credentials: 'include', cache: 'no-store', headers })
    let j = await r.json().catch(() => null)
    
    // 若接口明确返回未解锁或 code 为 500（解锁问题）
    if (j && (j.code === 500 || (j.success === false && /解锁/.test(String(j.message || ''))))) {
      const { storage } = await import('./storage.js')
      await storage.remove(['unlockCode', 'unlockTime', 'isUnlocked'])
      return { url: '', needUnlock: true }
    }
    
    let url = j && (j.result || j.message)
    if (url) return { url }
    
    // 若仍被拒绝，尝试在查询参数加入 token 兜底
    if (unlock && unlock.code) {
      const urlWithToken = api + `?token=${encodeURIComponent(sanitizeUnlockCode(unlock.code))}`
      r = await fetch(urlWithToken, { credentials: 'include', cache: 'no-store', headers })
      j = await r.json().catch(() => null)
      
      if (j && (j.code === 500 || (j.success === false && /解锁/.test(String(j.message || ''))))) {
        const { storage } = await import('./storage.js')
        await storage.remove(['unlockCode', 'unlockTime', 'isUnlocked'])
        return { url: '', needUnlock: true }
      }
      
      url = j && (j.result || j.message)
      if (url) return { url }
    }
  } catch (error) {
    console.error('Resolve stream error:', error)
  }
  
  // 兜底：若传入的是网页，尝试 HTML 提取（不推荐，低优先级）
  if (detailUrl && /^https?:\/\//.test(detailUrl)) {
    try {
      const res = await fetch(detailUrl, { credentials: 'omit', cache: 'no-store' })
      const html = await res.text()
      const link = findAudioUrl(html) || findAudioUrlFromScript(html)
      if (link) return { url: link }
    } catch (error) {
      console.error('HTML extraction error:', error)
    }
  }
  
  return { url: '' }
}

// 从 HTML 中提取音频 URL
function findAudioUrl(html) {
  const audioRegex = /(https?:[^\s"'<>]+\.(?:flac|mp3|m4a))(?:\?[\w=&%-]+)?/i
  const m = audioRegex.exec(html)
  return m ? m[1] : ''
}

// 从脚本中提取音频 URL
function findAudioUrlFromScript(html) {
  const scriptRegex = /(?:src|url)\s*[:=]\s*["'](https?:[^"']+\.(?:flac|mp3|m4a)[^"']*)["']/i
  const m = scriptRegex.exec(html)
  return m ? m[1] : ''
}

